package algorithm;

import java.util.Arrays;

public class Demo02 {//稀疏矩阵的转换和还原
    public static void main(String[] args) {
        System.out.println("--------------------------------------------------");//创造原矩阵
        int num = 10;
        int[][] arrInt = new int[num][num];
        arrInt[2][3] = 55;
        arrInt[5][5] = 33;
        for (int i = 0; i < num; i++) {
            for (int j = 0; j < num; j++) {
                System.out.print(arrInt[i][j]+ "\t");
            }
            System.out.println();
        }
        System.out.println("--------------------------------------------------");//原来的矩阵转换为稀疏矩阵
        int cnt = 0;
        for (int i = 0; i < num; i++) {
            for (int j = 0; j < num; j++) {
               if(arrInt[i][j]!=0){
                   cnt++;
               }
            }

        }
        int[][] arrxs = new int[cnt+1][3];
        arrxs[0][0]=10;
        arrxs[0][1]=10;
        arrxs[0][2]=cnt;
        cnt=1;
        for (int i = 0; i < num; i++) {
            for (int j = 0; j < num; j++) {
                if(arrInt[i][j]!=0){
                    arrxs[cnt][0] = i;
                    arrxs[cnt][1] = j;
                    arrxs[cnt++][2] = arrInt[i][j];
                }
            }
        }
        System.out.println(Arrays.deepToString(arrxs));
        System.out.println("--------------------------------------------------");//稀疏矩阵转换为原来的矩阵
        int[][] array = new int[arrxs[0][0]][arrxs[0][1]];
        for (int i = 1; i < arrxs.length; i++) {
            array[arrxs[i][0]][arrxs[i][1]] = arrxs[i][2];
        }
        for (int i = 0; i < arrxs[0][0]; i++) {
            for (int j = 0; j < arrxs[0][1]; j++) {
                System.out.print(array[i][j]+ "\t");
            }
            System.out.println();
        }
    }
}
